package com.woniu.park.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniu.park.controller.form.BalanceForm;
import com.woniu.park.controller.form.ParkspaceForm;
import com.woniu.park.dao.*;
import com.woniu.park.entity.*;
import com.woniu.park.service.IOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.woniu.park.util.PageResult;
import com.woniu.park.util.Result;
import com.woniu.park.util.Status;
import com.woniu.park.util.TimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author cxb
 * @since 2020-09-05
 */
@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {


    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private ParkspaceMapper parkspaceMapper;
    @Autowired
    private TotalorderMapper  totalorderMapper;
    @Autowired
    private CouponMapper couponMapper;
    /*
        @author xjy
        预约车位
     */
    @Override
    @Transactional
    public Result bookingSpace(BalanceForm balanceForm) {
        System.out.println(balanceForm.getUserId());
        ParkspaceForm parkspaceForm = new ParkspaceForm();
        parkspaceForm.setParkspaceId(balanceForm.getParkspaceId());
        parkspaceForm.setUserId(balanceForm.getUserId());
        parkspaceForm.setStoppingTime(balanceForm.getHours());
  //一：判断是否使用优惠券
        if(parkspaceForm.getCouponId()>0){
            Coupon coupon = couponMapper.selectById(parkspaceForm.getCouponId());
            System.out.println("优惠券："+coupon);
            //计算下单预约所需金额
            Parkspace parkspace = parkspaceMapper.selectById(parkspaceForm.getParkspaceId());
            //预约停车时间
            int stoppingTime = parkspaceForm.getStoppingTime();
                    //当消费额达到优惠券使用条件时
                if(coupon.getCouponCondition()<=parkspace.getParkspacePriceOther()*stoppingTime){
                    //查出用户余额
                    User user = userMapper.selectById(parkspaceForm.getUserId());
                    double userBalance = user.getUserBalance();
                    log.info("下单操作用户ID：{}",user.getUserId());
                    //消费额
                    double price = parkspace.getParkspacePriceOther()*stoppingTime-coupon.getCouponDiscount();
                    //3.执行下单操作
                    //①将车位状态改为已使用
                    UpdateWrapper<Parkspace> wrapper = new UpdateWrapper<>();
                    wrapper.set("parkspace_status",Status.PARKING_SPOT2).eq("parkspace_id",parkspace.getParkspaceId());
                    log.info("车位状态改：",Status.PARKING_SPOT2);
                    parkspaceMapper.update(null,wrapper);

                    //②新增order订单
                    Order order = new Order();
                    order.setOrderParkspaceId(parkspace.getParkspaceId());
                    order.setOrderPrice(price);
                    System.out.println("租几小时："+stoppingTime);
                    order.setOrderDay(stoppingTime);
                    order.setOrderParkspaceNum(parkspace.getParkspaceNum());
                    order.setOrderUserId(user.getUserId());
                    order.setOrderTime(new Date());
                    order.setOrderParkspaceId(parkspace.getParkspaceId());
                    order.setOrderStatus(Status.ORDER_STATUS0);
                    order.setOrderParkspaceStatus(Status.ORDER_STATUS0);
                    order.setOrderParkAddress(parkspace.getParkspaceAddress());
                    order.setOrderLicense(user.getUserLicense());
                    orderMapper.insert(order);
                    log.info("新增下单：{}",order);
                    UpdateWrapper<User> wrapper1 = new UpdateWrapper<>();
                    wrapper1.set("user_total_consumption",user.getUserTotalConsumption()+price).set("user_balance",userBalance-price).eq("user_id",user.getUserId());
                    userMapper.update(null,wrapper1);
                    log.info("用户消费额增加：{}",price);
                    //⑤优惠券减去（119-127下面未执行）
                    System.out.println("为什么");
                    UpdateWrapper<Coupon> couponUpdateWrapper = new UpdateWrapper<>();
                    System.out.println("why");
                    int gg = coupon.getCouponNumber()-1;
                    System.out.println("优惠券本身数量："+ coupon.getCouponNumber());
                    int uu =user.getUserId();
                    couponUpdateWrapper.set("coupon_number",gg).eq("user_id",uu);
                    System.out.println("优惠券减少");
                    couponMapper.update(null,couponUpdateWrapper);
                    log.info("优惠券使用数量减：{}",1);
                    return Result.success("1","用卷成功",order);
                }else{
                    return Result.fail("20008","未满足优惠券使用条件");
                }

        }else{
 //二：不是用优惠券
             //1.查出用户余额
            User user = userMapper.selectById(parkspaceForm.getUserId());
            double userBalance = user.getUserBalance();
            log.info("下单操作用户ID：{}",user.getUserId());
            //2.计算下单预约所需金额
            Parkspace parkspace = parkspaceMapper.selectById(parkspaceForm.getParkspaceId());
            //预约停车时间
            int stoppingTime = parkspaceForm.getStoppingTime();
            if(3>=stoppingTime){
                //3小时内
                double price = parkspace.getParkspacePriceHour()*stoppingTime;
                if (price<=userBalance){
                    //3.执行下单操作
                    //①将车位状态改为已使用
                    UpdateWrapper<Parkspace> wrapper = new UpdateWrapper<>();
                    wrapper.set("parkspace_status",Status.PARKING_SPOT2).eq("parkspace_id",parkspace.getParkspaceId());
                    log.info("车位状态改：{}",Status.PARKING_SPOT2);
                    parkspaceMapper.update(null,wrapper);
                    //②新增order订单
                    Order order = new Order();
                    order.setOrderParkspaceId(parkspace.getParkspaceId());
                    order.setOrderPrice(price);
                    order.setOrderDay(stoppingTime);
                    order.setOrderUserId(user.getUserId());
                    order.setOrderTime(new Date());
                    order.setOrderParkspaceNum(parkspace.getParkspaceNum());
                    order.setOrderParkspaceStatus(Status.ORDER_STATUS0);
                    order.setOrderStatus(Status.ORDER_STATUS0);
                    order.setOrderParkAddress(parkspace.getParkspaceAddress());
                    order.setOrderLicense(user.getUserLicense());
                    orderMapper.insert(order);
                    log.info("新增下单：{}",order);
                    UpdateWrapper<User> wrapper1 = new UpdateWrapper<>();
                    wrapper1.set("user_total_consumption",user.getUserTotalConsumption()+price).set("user_balance",userBalance-price).eq("user_id",user.getUserId());
                    userMapper.update(null,wrapper1);
                    log.info("用户消费额增加：{}",price);
                    return Result.success("1","未用卷，停车小于一小时",order);
                }else{
                    return  Result.fail("20006","余额不足请充值",userBalance);
                }
            }else{
                //其他(大于一小时)
                double price = parkspace.getParkspacePriceOther()*stoppingTime;
                //3.执行下单操作
                //①将车位状态改为已使用
                UpdateWrapper<Parkspace> wrapper = new UpdateWrapper<>();
                wrapper.set("parkspace_status",Status.PARKING_SPOT2).eq("parkspace_id",parkspace.getParkspaceId());
                log.info("车位状态改：",Status.PARKING_SPOT2);
                parkspaceMapper.update(null,wrapper);
                //②新增order订单
                Order order = new Order();
                order.setOrderParkspaceId(parkspace.getParkspaceId());
                order.setOrderPrice(price);
                order.setOrderDay(stoppingTime);
                order.setOrderUserId(user.getUserId());
                order.setOrderTime(new Date());
                order.setOrderParkspaceNum(parkspace.getParkspaceNum());
                order.setOrderLicense(user.getUserLicense());
                order.setOrderStatus(Status.ORDER_STATUS0);
                order.setOrderParkspaceStatus(Status.ORDER_STATUS0);
                order.setOrderParkAddress(parkspace.getParkspaceAddress());
                order.setOrderLicense(user.getUserLicense());
                orderMapper.insert(order);
                log.info("新增下单：{}",order);
                UpdateWrapper<User> wrapper1 = new UpdateWrapper<>();
                wrapper1.set("user_total_consumption",user.getUserTotalConsumption()+price).set("user_balance",userBalance-price).eq("user_id",user.getUserId());
                userMapper.update(null,wrapper1);
                log.info("用户消费额增加：{}",price);
                return Result.success("1","未用卷，停车大于一小时",order);
            }
        }
    }

    /*
        取消预约
     */
    @Override
    @Transactional
    public Result cancellationOrder(int userId) {
        //查询订单
        System.out.println("userId:"+userId);
        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.eq("order_user_id",userId).eq("order_parkspace_status",Status.ORDER_STATUS0);
        Order order = orderMapper.selectOne(orderQueryWrapper);
        System.out.println("order:"+order);
     /*   if (order==null){
            return Result.fail("20009","没有订单");
        }*/
        Date time = order.getOrderTime();
        //获取当前时间
       long presentTime = TimeUtil.presentTime().getTime();
       //下单时间
       long  orderTime = time.getTime()+30*60*1000;
       long wc = orderTime-presentTime;
        System.out.println("是否满足:"+wc);
       if(presentTime<=orderTime) {
           System.out.println("哎呀");
           if (order!=null){
               //用户退款,扣除2元手续费(消费总额也扣掉)
               double moeny = order.getOrderPrice()-2;
               double moenyTotal = order.getOrderPrice();
               User user = userMapper.selectById(userId);
               UpdateWrapper<User> wrapper1 = new UpdateWrapper<>();
               double alterBalance=user.getUserBalance()+moeny;
               double alterTotalConsumption = user.getUserTotalConsumption()-order.getOrderPrice();
               wrapper1.set("user_balance",alterBalance).set("user_total_consumption",alterTotalConsumption)
                       .eq("user_id",userId);
               userMapper.update(null,wrapper1);
               log.info("用户余额和消费总额修改：{},{}",alterBalance,alterTotalConsumption);
               //订单状态改变
               UpdateWrapper<Order> orderUpdateWrapper = new UpdateWrapper<>();
               orderUpdateWrapper.set("order_status",Status.ORDER_STATUS1).set("order_parkspace_status",Status.ORDER_STATUS3).eq("order_id",order.getOrderId());
               orderMapper.update(null,orderUpdateWrapper);
               log.info("订单表状态修改：{},{}",Status.ORDER_STATUS1,Status.ORDER_STATUS3);
               //车位状态改变，其他用户可进行预约
               UpdateWrapper<Parkspace> wrapper = new UpdateWrapper<>();
               wrapper.set("parkspace_status",Status.PARKING_SPOT1).eq("parkspace_id",order.getOrderParkspaceId());
               parkspaceMapper.update(null,wrapper);
               System.out.println("order.getOrderParkspaceId():"+order.getOrderParkspaceId());
               log.info("车位状态修改：{}",Status.ORDER_STATUS1);
               return Result.success("1","退款成功,扣除手续费2元");
           }else{
               return Result.fail("20009","没有可退款的订单");
           }
       }else{
           return Result.fail("20009","没有订单,或者没有订单满足退约条件");
       }

    }

    /*
        查看历史记录及消费明细
     */

    @Override
    public PageResult queryHistory(int pageIdx,int pageSize,int userId) {
        IPage<Order> page = new Page<>(pageIdx,pageSize);
        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();

        orderQueryWrapper.eq("order_user_id",userId).groupBy("order_time");
        IPage<Order> orderIPage = orderMapper.selectPage(page,orderQueryWrapper);
        long total = orderIPage.getTotal();
        List<Order> records = orderIPage.getRecords();
        log.info("查询总条数：{}，查询结果：{}",total,records);
        return PageResult.success(total,pageIdx,pageSize,records);
    }

    @Override
    public IPage<Order> pageQuery(int pageIdx, int pageSize, int orderParkspaceId, Date orderSpacerecordTimeStart, Date orderSpacerecordTimeEnd) {
        Page<Order> page = new  Page<>(pageIdx,pageSize);
        IPage<Order> orderIPage = orderMapper.pageQueryOrder(page, orderParkspaceId, orderSpacerecordTimeStart, orderSpacerecordTimeEnd);

        return orderIPage;
    }

    @Override
    public int insertOrder(int userId, double parseMoney, String parkspaceId,int stoppingTime) {
        Order order = new Order();
        order.setOrderUserId(userId);
        order.setOrderPrice(parseMoney);
        order.setOrderStatus(Status.ORDER_STATUS0);
        order.setOrderParkspaceStatus(Status.ORDER_STATUS0);

        order.setOrderParkspaceId(Integer.parseInt(parkspaceId));
        //根据车位id查询相关信息
        Parkspace parkspace = parkspaceMapper.selectById(parkspaceId);
        order.setOrderParkspaceNum(parkspace.getParkspaceNum());
        order.setOrderParkAddress(parkspace.getParkspaceAddress());
        order.setOrderDay(stoppingTime);
        orderMapper.insert(order);
        //修改车位状态
        parkspace.setParkspaceStatus(Status.PARKING_SPOT2);

        parkspaceMapper.updateById(parkspace);

        //返回主键值
        return order.getOrderId();
    }

    @Override
    public Order unfinishedOrder(int userId) {
        //通过userid查出该用户已经下的订单
        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.eq("order_user_id",userId).eq("order_parkspace_status", Status.ORDER_STATUS0);
        Order order = orderMapper.selectOne(orderQueryWrapper);
        return order;
    }
    /*
           短信验证登录
        */
    @Override
    public boolean send(String phoneNum, String templateCode, Map<String, Object> code) {
        //  连接阿里云  第二个参数是密钥id 第三个参数是密码
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAI4GGwZ2293tuSLAZWZVYb", "twnQYr4F5yFF83m6IN9AOaDTUuPfEy");
        IAcsClient client = new DefaultAcsClient(profile);
        //构件请求
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");//定死不修改
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        //自定义的参数（手机号，签名，模板,验证码！）
        request.putQueryParameter("PhoneNumbers", phoneNum);
        request.putQueryParameter("SignName", "蜗牛共享车位");
        request.putQueryParameter("TemplateCode", templateCode);
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(code));
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            return response.getHttpResponse().isSuccess();
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return false;
    }

}
